package com.ltu.timkor6.gamesite.admin.server;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.ltu.timkor6.gamesite.admin.client.AdminService;
import com.ltu.timkor6.gamesite.server.Encrypter;
import com.ltu.timkor6.gamesite.server.GameSiteServiceImpl;
import com.ltu.timkor6.gamesite.shared.DBUsers;
import com.ltu.timkor6.gamesite.shared.UserInfo;

@SuppressWarnings("serial")
public class AdminServiceImpl extends GameSiteServiceImpl implements AdminService
{
	
	public AdminServiceImpl()
	{
		// TODO Auto-generated constructor stub
	}
	
	@SuppressWarnings("unchecked")
	public List<UserInfo> getUserList()
	{
		PersistenceManager pm = this.getPersistenceManager();
		
		List<UserInfo> list = new ArrayList<UserInfo>();
		try
		{
			Query q = pm.newQuery("select from " + DBUsers.class.getName() + " order by createdDate desc");
			List<DBUsers> db = (List<DBUsers>) q.execute();
			for(DBUsers info : db)
			{
				UserInfo userInfo = setUserInfo(info);
				
				list.add(userInfo);
			}
		}
		finally
		{
			pm.close();
		}
		
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public UserInfo getUserInfo(long id)
	{
		UserInfo userInfo = null;
		
		PersistenceManager pm = this.getPersistenceManager();
		
		try
		{
			Query query = pm.newQuery(DBUsers.class, "id == " + id);
			Collection<DBUsers> collection = (Collection<DBUsers>) query.execute();
			DBUsers info = collection.iterator().next();
			
			if(info != null)
			{
				userInfo = setUserInfo(info);
			}
		}
	    catch (Throwable t)
	    {
	    	t.printStackTrace();
	    }
		finally
		{
			pm.close();
		}
		
		return userInfo;
	}
	
	@SuppressWarnings("unchecked")
	public boolean setUserInfo(UserInfo userInfo)
	{
		boolean status = false;
		
		// Update user
		PersistenceManager pm = this.getPersistenceManager();
		try
		{
			pm.currentTransaction().begin();
			
			Query query = pm.newQuery(DBUsers.class, "id == " + userInfo.getId());
			Collection<DBUsers> collection = (Collection<DBUsers>) query.execute();
			DBUsers info = collection.iterator().next();
			
			if(info != null)
			{
				if(userInfo.getPassword() != null && 0 < userInfo.getPassword().length())
				{
					String password = Encrypter.getInstance().encrypt(userInfo.getPassword());
					info.setPassword(password);
				}
				info.setEmail(userInfo.getEmail());
				info.setIsTestUser(userInfo.isTestUser());
				info.setIsAdmin(userInfo.isAdmin());
				
				pm.currentTransaction().commit();
				
				status = true;
			}
		}
	    catch (Throwable t)
	    {
	    	// Rollback in case of errors
	    	t.printStackTrace();
	    	pm.currentTransaction().rollback();
	    }
		finally
		{
			pm.close();
		}
		
		return status;
	}
}
